package com.liws.hellofeiginclient.service;

import com.liws.hellocommon.entity.Person;
import com.liws.hellofeiginclient.feigin.ProductClient;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

/**
 * @Author: liweisheng
 * @Dcscription:
 * @Date: 2021/11/22 15:15
 */
@Slf4j
@Service
public class HystrixService {
    @Autowired
    private ProductClient productClient;

    @HystrixCommand(fallbackMethod = "hystrixFallBack")
    public List<Person> postHystrixByObject(@RequestBody Person person){

        return productClient.postFeiginByObject(person);
    }

    @HystrixCommand(fallbackMethod = "hystrixFallBack")
    @CacheResult(cacheKeyMethod = "genCacheKey")
    public List<Person> postHystrixCacheByObject(@RequestBody Person person){

        return productClient.postFeiginByObject(person);
    }

    public List<Person> hystrixFallBack(@RequestBody Person person, Throwable throwable) {

        String info="consumer 服务熔断,Reason:" + ExceptionUtils.getRootCauseMessage(throwable);
        log.warn(info);
        return null;
    }

    @HystrixCommand
    @CacheRemove(commandKey = "getProvider", cacheKeyMethod = "genCacheKey")
    public void updateProvider(@RequestBody Person person) {

        log.info("[updateProvider][更新服务提供者({})详情]", person);
    }

    public String genCacheKey(@RequestBody Person person) {

        return "PROVIDER_" + person;
    }
}
